package utils

import (
	"encoding/json"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"github.com/pkg/errors"
	"strings"
)

type responseContent struct {
	Message   string
	RequestId string
	BizId     string
	Code      string
}

var client *sdk.Client
var signName string

func init() {
	var err error
	accessSecret := beego.AppConfig.String("accessSecret")
	accessKeyId := beego.AppConfig.String("accessKeyId")
	signName = beego.AppConfig.String("signName")
	client, err = sdk.NewClientWithAccessKey("cn-hangzhou", accessKeyId, accessSecret)
	if err != nil {
		panic(err)
	}
}

func SendAliCheckSms(telephone string, checkCode string, templateCode string) (string, error) {
	request := requests.NewCommonRequest()
	request.Method = "POST"
	request.Scheme = "https" // https | http
	request.Domain = "dysmsapi.aliyuncs.com"
	request.Version = "2017-05-25"
	request.ApiName = "SendSms"
	request.QueryParams["RegionId"] = "cn-hangzhou"
	request.QueryParams["PhoneNumbers"] = telephone
	request.QueryParams["SignName"] = signName
	request.QueryParams["TemplateCode"] = templateCode
	if checkCode != "" {
		checkCode = strings.ReplaceAll(checkCode, "\"", "\\\"")
		request.QueryParams["TemplateParam"] = "{code:\"" + checkCode + "\"}"
	}
	response, err := client.ProcessCommonRequest(request)
	if err != nil {
		return "", err
	}
	var content responseContent
	err = json.Unmarshal(response.GetHttpContentBytes(), &content)
	if err == nil {
		if content.Code == "OK" {
			logs.Info("SendAliCheckSms Success:%s,%s,%s", telephone, checkCode, content)
			return "OK", nil
		} else {
			logs.Error("SendAliCheckSms Error:%s,%s,%s", telephone, checkCode, content)
			return "", errors.New(content.Message)
		}
	}
	return "", err
}
